package com.yingsheng.bi.hks.template.biz;

import com.yingsheng.bi.hks.basic.ReqContext;
import com.yingsheng.bi.hks.basic.consts.MsgDict;
import com.yingsheng.bi.hks.basic.consts.NameDict;
import com.yingsheng.bi.hks.basic.exception.ServiceRuntimeException;
import com.yingsheng.bi.hks.basic.utils.HttpUtils;
import com.yingsheng.bi.hks.basic.utils.JwtUtils;
import com.yingsheng.bi.hks.repository.redis.SubjectRedisService;
import com.yingsheng.bi.hks.template.events.Event;
import com.yingsheng.bi.hks.template.processor.Processor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

@Slf4j
public class AccessTokenProcessor implements Processor {

    @Autowired
    private SubjectRedisService subjectRedisService;

    @Override
    public void exec(Event event) {
        String accessToken = HttpUtils.getRequestHeader(NameDict.ACCESS_TOKEN);
        if (StringUtils.hasText(accessToken)) {
            String identity = JwtUtils.validate(accessToken);
            if (log.isDebugEnabled()) {
                log.debug("Identity [" + identity + "]");
                log.debug("AccessToken [" + accessToken + "]");
            }
            if (subjectRedisService.getUser(identity) == null) {
                throw new ServiceRuntimeException(MsgDict.ACCESS_TOKEN_REQUIRED);
            }
            ReqContext.create(identity);
        } else {
            throw new ServiceRuntimeException(MsgDict.ACCESS_TOKEN_REQUIRED);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
